<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  'global_default_function.php';

function getCampaign($header, $database, $user) {
	$doResponse = HttpPost('https://api.baidu.com/json/sms/service/CampaignService/getCampaign', $header);
	$bodyArray = json_decode($doResponse, true);
	if(is_array($bodyArray['body']['data'])) {
		$campaignIdArray = [];
		foreach ( $bodyArray['body']['data'] as $value ) {
			array_push($campaignIdArray, $value['campaignId']);
			$negativeWords = serialize($value['negativeWords']);
			$exactNegativeWords = serialize($value['exactNegativeWords']);
			$value['budget'] = isset($value['budget']) ? $value['budget'] : 0;
			$res = $database->query("select id from cfg_campaign where `companyId` = '{$user['companyId']}' AND `campaignId` = '{$value['campaignId']}' LIMIT 1");
			if( isset($res[0]['id']) ) {
				$database->query( " UPDATE cfg_campaign SET `customerid` = '{$user['customerid']}', `contact` = '{$user['contact']}', `campaignName` = '{$value['campaignName']}', `budget` = '{$value['budget']}',
					`datatime` = NOW(), `negativeWords` = '{$negativeWords}', `exactNegativeWords` = '{$exactNegativeWords}', `status` = '{$value['status']}' WHERE id = '{$res[0]['id']}'; ");
			} else {
				$database->query("INSERT INTO cfg_campaign ( `companyId`, `customerid`, `contact`, `userType`, `userId`, `bazaarId`, `budget`, `datatime`, `campaignid`, `campaignName`, `negativeWords`, `exactNegativeWords`, `status` ) values (
					'{$user['companyId']}', '{$user['customerid']}', '{$user['contact']}', 1, '{$user['userid']}', '{$user['bazaarId']}', '{$value['budget']}', NOW(), '{$value['campaignId']}', '{$value['campaignName']}', '{$negativeWords}', '{$exactNegativeWords}',
					'{$value['status']}') " );
			}
		}
		if(count($campaignIdArray) > 0) {
			$campaignIdStr = implode(',', $campaignIdArray);
			$database->query(" DELETE FROM cfg_campaign WHERE `companyId` = '{$user['companyId']}' AND `userType` = 1 AND `userId` = {$user['userid']} AND `campaignId` NOT IN ($campaignIdStr); " );
		}
	}
}

run(function() use ($argv) {
	showMessage('获取计划数据.' );

	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}
	
  $userList = $database->query('SELECT `id`, `companyId`, `userid`, `username`, `password`, `token`, `bazaarId`, `customerid`, `contact` FROM cfg_expand where status = 1 and userType = 1');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}
	
	$userArray = array_chunk($userList, $config['curlnumber']);
  foreach ($userArray as $arrayList) {
		foreach ($arrayList as $user) {
			go(function() use ($config, $user)  {
				$database = new MySQL;
				$connect = $database->connect($config);
				if( $connect === false) {
					return;
				}
				showMessage($user['username'].'获取计划数据.' );
				getCampaign(json_encode([
					'header'=>['username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token']],
					'body'=> [
						"campaignFields"=> [
								"campaignId",
								"campaignName",
								"budget",
								"negativeWords",
								"exactNegativeWords",
								"status",
						],
						"mobileExtend"=> 1,
						"adType"=> 0
					]
				]), $database, $user);
			});
		}
	}
	
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');